/**
 * 分镜导出工具函数
 * 支持多种格式导出分镜数据
 */

import { StoryboardProject } from '../../types/storyboardProject'
import { StoryboardData } from '../../types/document'

export interface StoryboardRow {
  id: string
  order: number
  image?: string
  shotType: string
  duration: number
  content: string
  notes: string
  [key: string]: any
}

/**
 * 将分镜数据转换为CSV格式
 */
export function exportStoryboardToCSV(
  project: StoryboardProject,
  rows: StoryboardRow[],
  customColumns: any[] = []
): string {
  const headers = [
    '序号',
    '景别',
    '时长(秒)',
    '内容描述',
    '备注',
    ...customColumns.map(col => col.title)
  ]
  
  const csvRows = [
    headers.join(','),
    ...rows.map(row => {
      const basicData = [
        row.order,
        `"${row.shotType}"`,
        row.duration,
        `"${row.content.replace(/"/g, '""')}"`,
        `"${row.notes.replace(/"/g, '""')}"`,
        ...customColumns.map(col => {
          const value = row[col.dataIndex] || ''
          return `"${String(value).replace(/"/g, '""')}"`
        })
      ]
      return basicData.join(',')
    })
  ]
  
  return csvRows.join('\n')
}

/**
 * 将分镜数据转换为Markdown格式
 */
export function exportStoryboardToMarkdown(
  project: StoryboardProject,
  rows: StoryboardRow[],
  customColumns: any[] = []
): string {
  const markdown = `# ${project.name}

${project.description ? `> ${project.description}\n` : ''}

**项目信息**：
- 创建时间：${new Date(project.createdAt).toLocaleString()}
- 场景总数：${rows.length}
- 总时长：${rows.reduce((sum, row) => sum + row.duration, 0)}秒

## 分镜列表

| 序号 | 景别 | 时长(秒) | 内容描述 | 备注 |${customColumns.map(col => ` ${col.title} |`).join('')}
|------|------|----------|----------|------|${customColumns.map(() => '-----|').join('')}
${rows.map(row => {
  const basicCells = [
    row.order,
    row.shotType,
    row.duration,
    row.content.replace(/\|/g, '\\|'),
    row.notes.replace(/\|/g, '\\|')
  ]
  const customCells = customColumns.map(col => {
    const value = row[col.dataIndex] || ''
    return String(value).replace(/\|/g, '\\|')
  })
  return `| ${[...basicCells, ...customCells].join(' | ')} |`
}).join('\n')}

---
*导出时间：${new Date().toLocaleString()}*
`
  
  return markdown
}

/**
 * 将分镜数据转换为HTML格式
 */
export function exportStoryboardToHTML(
  project: StoryboardProject,
  rows: StoryboardRow[],
  customColumns: any[] = []
): string {
  const customColumnHeaders = customColumns.map(col => `<th>${col.title}</th>`).join('')
  const customColumnCells = (row: StoryboardRow) => 
    customColumns.map(col => `<td>${row[col.dataIndex] || ''}</td>`).join('')

  return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${project.name} - 分镜脚本</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
            margin: 40px;
            line-height: 1.6;
            color: #333;
        }
        .header {
            border-bottom: 2px solid #1890ff;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .project-info {
            background: #f5f5f5;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 30px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        th, td {
            border: 1px solid #e8e8e8;
            padding: 12px 8px;
            text-align: left;
            vertical-align: top;
        }
        th {
            background: #fafafa;
            font-weight: 600;
            color: #333;
        }
        tr:nth-child(even) {
            background: #fafafa;
        }
        .shot-image {
            max-width: 120px;
            max-height: 80px;
            border-radius: 4px;
        }
        .footer {
            margin-top: 40px;
            text-align: center;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>${project.name}</h1>
        ${project.description ? `<p>${project.description}</p>` : ''}
    </div>
    
    <div class="project-info">
        <h3>项目信息</h3>
        <p><strong>创建时间：</strong>${new Date(project.createdAt).toLocaleString()}</p>
        <p><strong>场景总数：</strong>${rows.length}</p>
        <p><strong>总时长：</strong>${rows.reduce((sum, row) => sum + row.duration, 0)}秒</p>
    </div>

    <table>
        <thead>
            <tr>
                <th>序号</th>
                <th>画面</th>
                <th>景别</th>
                <th>时长(秒)</th>
                <th>内容描述</th>
                <th>备注</th>
                ${customColumnHeaders}
            </tr>
        </thead>
        <tbody>
            ${rows.map(row => `
                <tr>
                    <td>${row.order}</td>
                    <td>${row.image ? `<img src="${row.image}" class="shot-image" alt="分镜图片">` : '暂无图片'}</td>
                    <td>${row.shotType}</td>
                    <td>${row.duration}</td>
                    <td>${row.content}</td>
                    <td>${row.notes}</td>
                    ${customColumnCells(row)}
                </tr>
            `).join('')}
        </tbody>
    </table>

    <div class="footer">
        <p>导出时间：${new Date().toLocaleString()}</p>
    </div>
</body>
</html>`
}

/**
 * 下载文件
 */
export function downloadFile(content: string, filename: string, mimeType: string) {
  const blob = new Blob([content], { type: mimeType })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

/**
 * 导出分镜为不同格式
 */
export function exportStoryboard(
  project: StoryboardProject,
  rows: StoryboardRow[],
  customColumns: any[] = [],
  format: 'csv' | 'markdown' | 'html' = 'csv'
) {
  const timestamp = new Date().toISOString().slice(0, 16).replace(/:/g, '-')
  const baseFilename = `${project.name}_分镜脚本_${timestamp}`
  
  switch (format) {
    case 'csv':
      const csvContent = exportStoryboardToCSV(project, rows, customColumns)
      downloadFile(csvContent, `${baseFilename}.csv`, 'text/csv;charset=utf-8')
      break
    
    case 'markdown':
      const markdownContent = exportStoryboardToMarkdown(project, rows, customColumns)
      downloadFile(markdownContent, `${baseFilename}.md`, 'text/markdown;charset=utf-8')
      break
    
    case 'html':
      const htmlContent = exportStoryboardToHTML(project, rows, customColumns)
      downloadFile(htmlContent, `${baseFilename}.html`, 'text/html;charset=utf-8')
      break
  }
}